<template>
  <div class="pagetitle">
    <h2>공지사항 등록</h2>
  </div>
  <section class="section">
    <div class="card">
      <div class="card-body pt-3">
        <table class="form-table" style="width: 100%;">
          <tbody>
            <tr>
              <th class="text-lf">
                <span>제목</span>
              </th>
              <td>
                <input
                  type="text"
                  class="form-control"
                  v-model="notice.title"
                  placeholder="제목을 입력하세요."
                />
              </td>
            </tr>
            <tr class="border-top">
              <th colspan="4" class="text-lf">
                <span>내용</span>
              </th>
            </tr>
            <tr style="max-height: 600px">
              <td colspan="4" style="height: 100%" class="pt-0">
                <textarea name="editor" id="editor" class="form-control" style="width:100%"></textarea>
              </td>
            </tr>

            <!-- 첨부파일 -->
            <tr class="border-top">
              <th class="text-lf">
                첨부파일
              </th>
              <td colspan="2">
                <div class="gd-12 pr0">
                  <div class="gd-2 pl0 pr0">
                    <label for="file" class="btn btn-outline-primary">파일찾기</label>
                    <input
                      type="file"
                      id="file"
                      ref="file"
                      @change="handleFileInsert"
                      multiple
                    />
                  </div>
                  <div class="gd-12 pl0 pr0" v-if="fileList.length > 0">
                    <ul>
                      <li
                        v-for="(file, idx) in fileList"
                        :key="idx"
                        class="pd-10 mt-10"
                      >
                        <div v-if="file.name" class="flex justify-between file-wrap">
                          <p>{{ file.name }}</p>
                          <button class="del-btn" @click="handleFileDelete(file, idx)">
                            X
                          </button>
                        </div>
                      </li>
                    </ul>
                  </div>
                </div>
              </td>
            </tr>

            <!-- 공지글 -->
            <tr class="border-top">
              <th class="text-lf">
                공지글
              </th>
              <td colspan="3">
                <div class="d-flex no-gutters">
                  <div class="col-md-4">
                    <input
                      type="radio"
                      name="notice"
                      id="notice-y"
                      class="mr5"
                      value="Y"
                      v-model="notice.isNotice"
                    />
                    <label for="notice-y">사용</label>
                  </div>
                  <div class="col-md-4">
                    <input
                      type="radio"
                      name="notice"
                      id="notice-n"
                      class="mr5"
                      value="N"
                      v-model="notice.isNotice"
                    />
                    <label for="notice-n">미사용</label>
                  </div>
                </div>
              </td>
            </tr>

            <!-- 공지글 게시기간 -->
            <tr class="border-top">
              <th class="text-lf">
                공지글 게시기간
              </th>
              <td colspan="3">
                <div class="d-flex no-gutters">
                  <div class="col-md-4">
                    <input
                      type="datetime-local"
                      class="form-control"
                      v-model="notice.startDate"
                      @change="checkDateValidity('startDate', $event)"
                    />
                  </div>
                  <div class="pd-1">-</div>
                  <div class="col-md-4">
                    <input
                      type="datetime-local"
                      class="form-control"
                      v-model="notice.endDate"
                      @change="checkDateValidity('endDate', $event)"
                    />
                  </div>
                </div>
              </td>
            </tr>

            <!-- 비밀글 -->
            <tr class="border-top">
              <th class="text-lf">
                비밀글
              </th>
              <td colspan="3">
                <div class="d-flex no-gutters">
                  <div class="col-md-4">
                    <input
                      type="radio"
                      name="private"
                      id="private-y"
                      class="mr5"
                      value="Y"
                      v-model="notice.isPrivate"
                    />
                    <label for="private-y">사용</label>
                  </div>
                  <div class="col-md-4">
                    <input
                      type="radio"
                      name="private"
                      id="private-n"
                      class="mr5"
                      value="N"
                      v-model="notice.isPrivate"
                    />
                    <label for="private-n">미사용</label>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <div class="text-end">
          <button class="btn btn-primary" @click="handleInsert">
            {{ notice.id == null ? "등록" : "수정" }}
          </button>
          <button class="btn btn-secondary" @click="handleCancel">취소</button>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
import UploadAdapter from './UploadAdapter.js'


export default {
  data() {
    return {
      editor: null,
      notice: {
        id: null,
        title: "",
        isNotice: "Y",
        startDate: null,
        endDate: null,
        isPrivate: "N",
        
      },
      fileList: [],
    };
  },
  methods: {
    handleCancel() {
      if (!confirm("등록을 취소하시겠습니까?")) {
        return;
      }
      this.$router.push({ path: "/list.page" });
    },

    handleFileInsert() {
      this.fileList = [...this.fileList, ...Array.from(this.$refs.file.files)];
    },

    handleFileDelete(file, index) {
      this.fileList.splice(index, 1);
    },

    handleInsert() {
      if (!this.validate()) {
        return;
      }

      if (this.notice.id == null) {
        this.saveNotice();
      } else {
        this.updateNotice();
      }
    },

    saveNotice() {
      alert("공지사항이 등록되었습니다.");
      this.$router.push({ path: "/view.page", query: { pageId: this.notice.id } });
    },

    updateNotice() {
      alert("공지사항이 수정되었습니다.");
      this.$router.push({ path: "/view.page", query: { pageId: this.notice.id } });
    },

    validate() {
      if (!this.notice.title.trim()) {
        alert("제목을 입력해주세요.");
        return false;
      }

      if (!this.notice.content.trim()) {
        alert("내용을 입력해주세요.");
        return false;
      }

      if (this.notice.isNotice === "Y" && (!this.notice.startDate || !this.notice.endDate)) {
        alert("공지기간을 올바르게 설정해주세요.");
        return false;
      }

      return true;
    },

    checkDateValidity(field, event) {
      const val = event.target.value;
      if (field === "startDate" && this.notice.endDate && this.notice.endDate < val) {
        alert("시작일은 종료일보다 클 수 없습니다.");
        this.notice.startDate = null;
      } else if (field === "endDate" && this.notice.startDate && this.notice.startDate > val) {
        alert("종료일은 시작일보다 작을 수 없습니다.");
        this.notice.endDate = null;
      }
    },

    beforeUnmount() {
      if (this.editor) {
        this.editor.destroy().then(() => {
          this.editor = null;
        });
      }
    },

    MyCustomUploadAdapterPlugin: function(editor) {
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
            console.log('loader', loader);
            return new UploadAdapter(loader);
        }
    }
  },
  mounted() {
},

MyCustomUploadAdapterPlugin(editor) {
   editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
       console.log('loader', loader);
       return new UploadAdapter(loader);
   }
},
};
</script>

<style scoped>
td,
th {
  padding: 1rem;
}
th {
  width: 10rem;
}
#file {
  position: absolute;
  width: 0;
  height: 0;
  padding: 0;
  overflow: hidden;
  border: 0;
}
</style>
